<template>
  <div class="patrol-point-edit">
    <div class="form-header">
      <i class="el-icon-edit"></i> 编辑巡更点
      <span class="back-link" @click="goBack()">* 返回列表</span>
    </div>

    <div class="form-container">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="patrol-form"
      >
        <el-form-item label="所属小区" prop="communityId" required>
          <el-select
            v-model="form.communityId"
            placeholder="请选择小区"
            style="width: 100%"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属楼宇" prop="buildingId">
          <el-select
            v-model="form.buildingId"
            placeholder="请选择楼宇"
            style="width: 100%"
            :disabled="!form.communityId"
            @focus="checkCommunitySelected"
            @change="handleBuildingChange"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="巡更类别" prop="categoryId" required>
          <el-select
            v-model="form.categoryId"
            placeholder="请选择巡更类别"
            style="width: 100%"
            :loading="loading.category"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="巡更点名称" prop="pointName" required>
          <el-input
            v-model="form.pointName"
            placeholder="请输入人员巡更点"
          ></el-input>
          <div class="form-tip">巡更点名称不能重复，建议："楼栋+楼层+名称"</div>
        </el-form-item>

        <el-form-item label="巡更点编号" prop="locationCode" required>
          <el-input
            v-model="form.locationCode"
            placeholder="请输入巡更点位置编号"
          ></el-input>
        </el-form-item>

        <el-form-item label="位置选择" prop="location">
          <div class="location-input">
            <el-input
              v-model="form.location"
              placeholder="点击选择位置"
              readonly
            ></el-input>
            <el-button type="primary" @click="handAddress">选择位置</el-button>
          </div>
        </el-form-item>
        <el-form-item label="定位距离" prop="radiusM">
          <el-input v-model="form.radiusM"></el-input>
          <div class="form-tip">
            巡更定位距离，可输入10米，不输入时则不检查定位距离
          </div>
        </el-form-item>

        <el-form-item label="拍照要求" prop="photoRequired">
          <el-radio-group v-model="form.photoRequired">
            <el-radio :label="1">要求拍照</el-radio>
            <el-radio :label="0">无要求</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="submitForm('form')">
            <i class="el-icon-check"></i> 保存
          </el-button>
          <el-button @click="cancelForm">取消</el-button>
        </div>
      </el-form>
    </div>
    <Amap
      v-if="showAmapDialog"
      :visible.sync="showAmapDialog"
      :defaultMarker="defaultMarker"
      @onMarker="onMarker"
    />
  </div>
</template>

<script>
import Amap from "../amap/amap.vue";

export default {
  components: {
    Amap,
  },
  data() {
    return {
      patrolPointId: null,
      form: {
        communityId: "",
        buildingId: "",
        areaName: "",
        categoryId: "",
        pointName: "",
        locationCode: "",
        description: "",
        photoRequired: 1,
        status: 1,
        location: "",
        longitude: "",
        latitude: "",
        address: "",
        radiusM: ""
      },
      rules: {
        communityId: [
          { required: true, message: "请选择所属小区", trigger: "change" },
        ],
        buildingId: [
          { required: true, message: "请选择所属楼宇", trigger: "change" },
        ],
        categoryId: [
          { required: true, message: "请选择巡更类别", trigger: "change" },
        ],
        pointName: [
          { required: true, message: "请输入巡更点名称", trigger: "blur" },
        ],
        locationCode: [
          { required: true, message: "请输入巡更点位置编号", trigger: "blur" },
        ],
      },
      // 下拉框选项
      communityOptions: [],
      buildingOptions: [],
      categoryOptions: [],
      loading: {
        community: false,
        building: false,
        category: false,
      },
      // 地图相关
      showAmapDialog: false,
      defaultMarker: null,
    };
  },

  created() {
    // 获取路由参数中的ID
    this.patrolPointId =this.$route.query.patrolPointId;
    if (!this.patrolPointId) {
      this.$message.error('未获取到巡更点ID，请返回列表重试');
      return;
    }
    
    // 页面加载时获取小区数据
    this.fetchCommunityData();
    
    // 获取巡更类别数据
    this.fetchCategoryData();
    
    // 获取巡更点详情
    this.fetchPatrolPointDetail();
  },

  methods: {
    // 获取巡更点详情
    fetchPatrolPointDetail() {
      this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      this.$axios.get(`api/patrol-server/patrol/queryById/${this.patrolPointId}`)
        .then(response => {
          this.$loading().close();
          
          if (response.data && response.data.code === 200) {
            const data = response.data.data;
            
            // 填充表单数据
            this.form = {
              communityId: data.communityId,
              buildingId: data.buildingId,
              areaName: data.areaName,
              categoryId: data.categoryId,
              pointName: data.pointName,
              locationCode: data.locationCode,
              location: data.location,
              address: data.location,
              longitude: data.longitude,
              latitude: data.latitude,
              radiusM: data.radiusM,
              photoRequired: data.photoRequired,
              status: data.status
            };
            
            // 获取楼宇数据
            if (this.form.communityId) {
              this.fetchBuildingData(this.form.communityId);
            }
          } else {
            this.$message.error(response.data.message || '获取巡更点详情失败');
          }
        })
        .catch(error => {
          this.$loading().close();
          console.error('获取巡更点详情错误:', error);
          this.$message.error('网络错误，请稍后重试');
        });
    },

    // 获取小区数据
    fetchCommunityData() {
      this.loading.community = true;
      this.$axios.get('api/infrastructure-server/community/queryAll')
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.communityOptions = response.data.data.map(item => {
              return { value: item.id, label: item.name };
            });
          }
          this.loading.community = false;
        })
        .catch(error => {
          console.error('获取社区列表错误:', error);
          this.loading.community = false;
        });
    },

    // 获取楼宇数据
    fetchBuildingData(communityId) {
      if (!communityId) return;

      this.loading.building = true;
      this.buildingOptions = [];
      if (communityId !== this.form.communityId) {
        this.form.buildingId = "";
      }

      this.$axios.get(`api/infrastructure-server/building/queryById/${communityId}`)
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.buildingOptions = response.data.data.map(item => {
              return { value: item.id, label: item.name };
            });
          }
          this.loading.building = false;
        })
        .catch(error => {
          console.error('获取楼宇列表错误:', error);
          this.loading.building = false;
        });
    },

    // 小区变更时触发
    handleCommunityChange(value) {
      this.fetchBuildingData(value);
    },

    // 楼宇变更时触发
    handleBuildingChange(value) {
      // 如果需要获取楼层等后续数据，可以在这里添加
    },

    // 检查是否已选择小区
    checkCommunitySelected() {
      if (!this.form.communityId) {
        this.$message({
          message: "请先选择所属小区",
          type: "warning",
        });
      }
    },
    
    //打开地图弹框
    handAddress() {
      // 判断是否已经选择了位置，已经选择了就回显位置
      let defaultMarker = null;
      if (this.form.address && this.form.latitude && this.form.longitude) {
        defaultMarker = {
          address: this.form.address,
          location: {
            lng: this.form.longitude,
            lat: this.form.latitude,
          },
        };
      } else {
        // 如果没有选择位置，设置默认中心坐标为118.83, 31.93
        defaultMarker = {
          address: "",
          location: {
            lng: 118.83,
            lat: 31.93,
          },
        };
      }
      this.defaultMarker = defaultMarker;
      this.showAmapDialog = true;
    },

    // 地址回调
    onMarker(e) {
      if (e) {
        // 更新地址和坐标到表单
        this.form.location = e.address;
        this.form.address = e.address;

        // 如果需要保留经纬度单独字段（根据后端需求）
        this.form.longitude = e.location.lng;
        this.form.latitude = e.location.lat;
      } else {
        // 清空数据
        this.form.location = "";
        this.form.address = "";
        this.form.longitude = "";
        this.form.latitude = "";
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 显示加载状态
          this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          
          // 构建要提交的数据
          const submitData = {
            pointId: this.patrolPointId,  // 添加ID用于更新
            communityId: this.form.communityId,
            buildingId: this.form.buildingId,
            categoryId: this.form.categoryId,
            pointName: this.form.pointName,
            locationCode: this.form.locationCode,
            location: this.form.address,
            longitude: this.form.longitude,
            latitude: this.form.latitude,
            radiusM: this.form.radiusM || 0, // 如果没有输入，默认为0
            photoRequired: this.form.photoRequired,
            status: this.form.status
          };
          
          // 发送请求更新数据
          this.$axios.post('api/patrol-server/patrol/update', submitData)
            .then(response => {
              // 关闭加载动画
              this.$loading().close();
              
              if (response.data && response.data.code === 200) {
                this.$message({
                  message: '巡更点更新成功',
                  type: 'success'
                });
                
                // 更新成功后返回列表页
                setTimeout(() => {
                  this.$router.push('/patrolPointDisplay');
                }, 1000);
              } else {
                this.$message({
                  message: response.data.message || '保存失败',
                  type: 'error'
                });
              }
            })
            .catch(error => {
              // 关闭加载动画
              this.$loading().close();
              
              console.error('更新巡更点数据错误:', error);
              this.$message({
                message: '网络错误，请稍后重试',
                type: 'error'
              });
            });
        } else {
          console.log('表单验证失败');
          this.$message({
            message: '请完善表单信息',
            type: 'warning'
          });
          return false;
        }
      });
    },

    cancelForm() {
      // 重置表单或返回列表
      this.$confirm("是否放弃编辑并返回列表?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$router.go(-1);
        })
        .catch(() => {});
    },

    goBack() {
      this.$router.go(-1);
    },

    // 获取巡更类别数据
    fetchCategoryData() {
      this.loading.category = true;
      // API调用获取巡更类别
      this.$axios.get('api/patrol-server/patrolCategory/queryAll')
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.categoryOptions = response.data.data.map(item => {
              return { value: item.id || item.categoryId, label: item.name || item.categoryName };
            });
          }
        })
        .catch(error => {
          console.error('获取巡更类别列表错误:', error);
        })
        .finally(() => {
          this.loading.category = false;
        });
    },
  },
};
</script>

<style scoped>
.patrol-point-edit {
  background-color: #f5f7fa;
  padding: 20px;
  height: 100%;
}

.form-header {
  background-color: #fff;
  padding: 15px 20px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 4px 4px 0 0;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
}

.back-link {
  color: #409eff;
  font-size: 14px;
  font-weight: normal;
  cursor: pointer;
}

.form-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 0 0 4px 4px;
  display: flex;
  justify-content: center;
}

.patrol-form {
  max-width: 600px;
  width: 100%;
}

.form-tip {
  font-size: 12px;
  color: #aaa;
  margin-top: 5px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.location-input {
  display: flex;
  width: 100%;
}

.location-input .el-input {
  margin-right: 10px;
}
</style>